package com.eic.framework.core.domain;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import io.swagger.annotations.ApiModelProperty;

public interface BaseEntityQoPage<T> {
    @JsonIgnore
    ThreadLocal<PageDomain> pageDomain=new ThreadLocal();

    @JsonSetter
    @ApiModelProperty(value = "分页参数：每页显示记录数",position = 995)
    default void setPageSize(int pageSize){
        PageDomain pd=pageDomain.get();
        if(pd==null){
            pd=new PageDomain();
            pageDomain.set(pd);
        }
        pd.setPageSize(pageSize);
    }
    @JsonSetter
    @ApiModelProperty(value = "分页参数：当前页码,第一页1",position = 996)
    default void setPageNum(int pageNum){
        PageDomain pd=pageDomain.get();
        if(pd==null){
            pd=new PageDomain();
            pageDomain.set(pd);
        }
        pd.setPageNum(pageNum);
    }

    @JsonSetter
    @ApiModelProperty(value = "分页参数：排序列,数据库表字段名称",position = 997)
    default void setOrderByColumn(String orderByColumn){
        PageDomain pd=pageDomain.get();
        if(pd==null){
            pd=new PageDomain();
            pageDomain.set(pd);
        }
        pd.setOrderByColumn(orderByColumn);
    }
    @JsonSetter
    @ApiModelProperty(value = "分页参数：排序的方向,desc或者asc,默认asc",position = 998)
    default void setSortOrder(String sortOrder){
        PageDomain pd=pageDomain.get();
        if(pd==null){
            pd=new PageDomain();
            pageDomain.set(pd);
        }
        pd.setIsAsc(sortOrder);
    }

    @JsonSetter
    @ApiModelProperty(value = "分页参数：分页参数合理化,true或者false",position = 999)
    default void setReasonable(String reasonable){
        PageDomain pd=pageDomain.get();
        if(pd==null){
            pd=new PageDomain();
            pageDomain.set(pd);
        }
        pd.setReasonable(Boolean.parseBoolean(reasonable));
    }

    @JsonIgnore
    default Page<T> getPage(){
        int pageSize=10;
        int pageNum=1;
        PageDomain pd = pageDomain.get();
        if(pd==null){
            pd=new PageDomain();
        }
        if(pd.getPageSize()!=null){
            pageSize=pd.getPageSize();
        }
        if(pd.getPageNum()!=null){
            pageNum=pd.getPageNum();
        }
        Page<T> p=new Page<>(pageNum,pageSize);
        if (StringUtils.isNotBlank(pd.getOrderByColumn())) {
            String orderBy = SqlUtil.escapeOrderBySql(pd.getOrderByColumn());
            if("asc".equals(pd.getIsAsc())){
                p.addOrder(OrderItem.asc(orderBy));
            }else if("desc".equals(pd.getIsAsc())) {
                p.addOrder(OrderItem.desc(orderBy));
            }
        }
        return p;
    }
}
